import Vue from 'vue'
import Vuex from 'vuex'

import { login, loginInfo } from "@/api/login";
import storage from '@/utils/localStorage'//storage存储

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: '',
    xbsgUserInfo: storage.get('xbsgUserInfo')? storage.get('xbsgUserInfo'):{},
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    XBSG_SET_USERINFO: (state, userinfo) => {
      state.xbsgUserInfo = userinfo
    }
  },
  actions: {
    login({ commit, dispatch }, userInfo) {
      const { username, password } = userInfo
      return new Promise((resolve, reject) => {
        login({ username: username.trim(), password: password }).then(response => {
          storage.setToken(response.data.access_token);
          commit('SET_TOKEN', response.data.access_token)
          dispatch('getInfo')
          // // 获取全局消息数
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    getInfo({ commit }) {
      return new Promise((resolve, reject) => {
        loginInfo().then(response => {
          commit('XBSG_SET_USERINFO', response.data)
          storage.set('xbsgUserInfo', response.data)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    }
  },
  modules: {
  }
})
